package cn.gov.anhai.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

public class TokenGenerator {
    /**
     * 使用固定的解密秘钥
     */
    private static final String SECRET = "AHDYC2024";

    /**
     * @version: V1.0
     * @description: 生成token并验证token并解密token中的信息
     * @param: 绑定数据（key-value）
     * @return: java.lang.String 返回token
     **/
    public static String getToken(Map<String, String> datas) {
        try {
            //用秘钥生成签名
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            //默认头部+载荷（手机号/id）+签名=jwt
            JWTCreator.Builder b = JWT.create();
            for (String key : datas.keySet()) {
                b.withClaim(key, datas.get(key));
            }
            String jwtToken = b.sign(algorithm);
            return jwtToken;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @version: V1.0
     * @description: 根据token获得数据
     * @param: token
     * @return: 得到数据（key-value）|null表示错误
     **/
    public static Map<String, String> getInfo(String token) {
        try {
            // 根据用户信息userInfo生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 效验TOKEN
            verifier.verify(token);
            //返回token内容
            return getTokenInfo(token);
        } catch (Exception exception) {
            return null;
        }
    }

    /**
     * @version: V1.0
     * @Title: getUsername
     * @description: 从Token中解密获得Token中的信息
     * @param: token
     * @return: 到数据（key-value）|null表示错误
     **/
    private static Map<String, String> getTokenInfo(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Map<String, String> data = new HashMap<>();
            for (String key : jwt.getClaims().keySet()) {
                data.put(key, jwt.getClaim(key).asString());
            }
            return data;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String, String> data = new HashMap<>();
        data.put("phone", "123");
        data.put("card", "456");
        data.put("orderNum", "789");

        String token = getToken(data);
        System.out.println("token：" + token);

        Map<String, String> dataNew = getInfo(token);
        if (dataNew == null) {
            System.out.println("无效token");
        } else {
            System.out.println("phone：" + dataNew.get("phone"));
            System.out.println("card：" + dataNew.get("card"));
            System.out.println("orderNum：" + dataNew.get("orderNum"));
        }
    }
}